package com.csust.travel.controller;

import com.csust.travel.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import com.csust.travel.entity.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping("/books")
public class BooksController {
    @Autowired
    BooksMapper booksMapper;
    @Autowired
    TransactionMapper transactionMapper;
    @Autowired
    NewUsersMapper newUsersMapper;
    @Autowired
    private ResourceLoader resourceLoader;

    @Autowired
    StatisticsMapper statisticsMapper;

    @Autowired
    private GiftMapper giftMapper;

    @RequestMapping("/upload")
    public ResBean upload(MultipartFile imgFile) {
        try {

            // 获取原始文件名
            String originalFilename = imgFile.getOriginalFilename();
            System.out.println(originalFilename);

            // 获取文件扩展名
            String fileExtension = getFileExtension(originalFilename);

            // 生成新的文件名
            String newFileName = UUID.randomUUID().toString() + "." + fileExtension;
//            // 使用ResourceLoader获取相对路
            String targetPath = "classpath:/static/upload/";
            Resource resource = resourceLoader.getResource(targetPath);

            // 直接获取upload目录的File对象
            File targetDir = resource.getFile();

            if (!targetDir.exists()) {
                targetDir.mkdirs(); // 创建目录
            }

            // 创建目标文件对象
            File f = new File(targetDir,newFileName);

            // 将文件从临时位置复制到目标位置
            imgFile.transferTo(f);

            return new ResBean(true, "上传成功666", newFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResBean(false, "上传失败666");
    }

    // 获取文件扩展名的方法
    private String getFileExtension(String filename) {
        int dotIndex = filename.lastIndexOf('.');
        if (dotIndex == -1) {
            return ""; // 文件没有扩展名
        }
        return filename.substring(dotIndex + 1).toLowerCase(); // 返回扩展名
    }


    @RequestMapping("/transaction")
    public ResBean addTransaction(@RequestBody TransactionParams plainParams2) {
        transactionMapper.createNewTransaction(plainParams2);
        int generatedId = plainParams2.getId();
        return new ResBean(true, "成功", generatedId);
    }


    @RequestMapping("/all")
    public ResBean pageAll(@RequestBody pageDate pageData) {
        PageHelper.startPage(pageData.getCurrentPage(), pageData.getPageSize());
        List<Books> Items;
        Items = booksMapper.findAllItem();
        PageInfo<Books> commentPageInfo = new PageInfo<>(Items);
        return new ResBean(true, null, commentPageInfo);
    }


    @RequestMapping("/findOwner")
    public ResBean Ownpage(@RequestBody pageDate pageData) {
        PageHelper.startPage(pageData.getCurrentPage(), pageData.getPageSize());
        List<Books> Items;
        Items = booksMapper.findOwnItem(pageData.getOwner());
        PageInfo<Books> commentPageInfo = new PageInfo<>(Items);
        return new ResBean(true, null, commentPageInfo);
    }


    @RequestMapping("/buyBook")
    public ResBean buyBooks(@RequestBody BuyBookParams plainParams1) {
        Integer user_id = plainParams1.getUser_id();
        Integer seller_id=plainParams1.getSeller_id();
        Integer id = plainParams1.getId();
        Integer purchaseQuantity = plainParams1.getPurchaseQuantity();
        Integer rn = booksMapper.remainingQuantity(id);
        if (rn >= purchaseQuantity) {
            booksMapper.buyBooks(id, purchaseQuantity);
            booksMapper.addBuy(user_id);
            booksMapper.addSold(seller_id);
            return new ResBean(true, "购买成功666");
        } else {
            return new ResBean(false, "购买失败,库存仅剩" + rn + "本");
        }
    }

    @RequestMapping("/del")
    public ResBean delItem(Integer id) {
        try {
            booksMapper.delItem(id);
            return new ResBean(true, "删除成功666");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResBean(false, "删除失败");
    }

    @RequestMapping("/getOwnerInfo")
    public ResBean getOwnerInfo(Integer id) {
        try {
            OwnerInfo ownerInfo =new OwnerInfo();
            ownerInfo.setAvatar(newUsersMapper.getAvatar(id));
            ownerInfo.setCollege(newUsersMapper.getCollege(id));
            ownerInfo.setMajor(newUsersMapper.getMajor(id));
            ownerInfo.setQqnumber(newUsersMapper.getQqnumber(id));
            ownerInfo.setUsername(newUsersMapper.getUsername(id));
            return new ResBean(true, "删除成功666",ownerInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResBean(false, "删除失败");
    }



    @RequestMapping("/book_favorites")
    public ResBean FavItem(Integer user_id) {
        try {
            List<BookFavorites> item;
            item = booksMapper.getFavorites(user_id);

            return new ResBean(true, "",item);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResBean(false, "");
    }

    @RequestMapping("/getFavoritePage")
    public ResBean GetFavItem(Integer user_id) {
        try {
            List<Integer>items;
            items = booksMapper.getFavoritePage(user_id);
            List<Books> Items;
            Items = booksMapper.findAllFavorites(items);

            PageInfo<Books> favorites = new PageInfo<>(Items);
            return new ResBean(true, "",favorites);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResBean(false, "");
    }



    @RequestMapping("/star")
    public ResBean starFilled(@RequestBody PublishParams param1) {
        try {
            Integer id = param1.getId();
            Integer user_id = param1.getOwner();
            booksMapper.addFavorite(user_id);
            booksMapper.AddFavorite(user_id,id);
            return new ResBean(true, "收藏成功666");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResBean(false, "收藏失败");
    }


    @RequestMapping("/unStar")
    public ResBean unStarFilled(@RequestBody PublishParams param1) {
        try {
            Integer id = param1.getId();
            Integer user_id = param1.getOwner();
            booksMapper.removeFavorite(user_id);
            booksMapper.unHasFavorite(user_id,id);
            return new ResBean(true, "取消收藏成功666");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResBean(false, "取消收藏失败");
    }


    @RequestMapping("/hasPublish")
    public ResBean publishItem(@RequestBody PublishParams param1) {
        try {
            Integer id = param1.getId();
            Integer user_id = param1.getOwner();
            booksMapper.publishItem(id);
            booksMapper.addPublish(user_id);
            return new ResBean(true, "发布成功666");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResBean(false, "发布失败");
    }




    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public ResBean saveItem(@RequestBody Books item) {
        try {
            System.out.println(item);
            System.out.println(item.getOwner()+"   111");
            booksMapper.saveItem(item);
            return new ResBean(true, "新增书籍成功666");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResBean(false, "新增书籍失败666");
    }

    @RequestMapping("/one")
    public ResBean findOne(Integer id) {
        Books item = booksMapper.findOne(id);
        try {
            return new ResBean(true, null, item);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResBean(false, null);
        }
    }


    @RequestMapping("/update")
    public ResBean editItem(@RequestBody Books item) {
        try {
            booksMapper.editItem(item);
            return new ResBean(true, "编辑成功666");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResBean(false, "编辑失败666");
    }






    @RequestMapping("/page")
    public ResBean page(@RequestBody pageDate pageData) {
        PageHelper.startPage(pageData.getCurrentPage(), pageData.getPageSize());
        List<Books> Items;
        String queryString =pageData.getQueryString();
        String na = pageData.getNationality();
        if ((isEmptyString(queryString)) && (isEmptyString(na))) {
            Items = booksMapper.findAllItem();
        } else if (isEmptyString(queryString) && !isEmptyString(na)) {
            Items = booksMapper.findBooksByNationality(na);
        } else if (!isEmptyString(queryString) && isEmptyString(na)) {
            Items = booksMapper.findByQuery(queryString);
        } else {
            Items = booksMapper.findByFilters(queryString, na);
        }
        PageInfo<Books> buyBookOnlyPageInfo = new PageInfo<>(Items);
        return new ResBean(true, null, buyBookOnlyPageInfo);
    }


    @RequestMapping("/publish")
    public ResBean publishBook(@RequestBody pageDate pageData) {
        PageHelper.startPage(pageData.getCurrentPage(), pageData.getPageSize());
        List<Books> Items;
        String queryString =pageData.getQueryString();
        String na = pageData.getNationality();
        Integer user_id = pageData.getOwner();
        if ((isEmptyString(queryString)) && (isEmptyString(na))) {
            Items = booksMapper.findPublish(user_id);
        } else if (isEmptyString(queryString) && !isEmptyString(na)) {
            Items = booksMapper.findBooksByNationality(na);
        } else if (!isEmptyString(queryString) && isEmptyString(na)) {
            Items = booksMapper.findByQuery(queryString);
        } else {
            Items = booksMapper.findByFilters(queryString, na);
        }
        PageInfo<Books> buyBookOnlyPageInfo = new PageInfo<>(Items);
        return new ResBean(true, null, buyBookOnlyPageInfo);
    }

    @RequestMapping("/published")
    public ResBean publishedBook(@RequestBody pageDate pageData) {
        PageHelper.startPage(pageData.getCurrentPage(), pageData.getPageSize());
        List<Books> Items;
        String queryString =pageData.getQueryString();
        String na = pageData.getNationality();
        Integer user_id = pageData.getOwner();
        if ((isEmptyString(queryString)) && (isEmptyString(na))) {
            Items = booksMapper.findPublished(user_id);
        } else if (isEmptyString(queryString) && !isEmptyString(na)) {
            Items = booksMapper.findBooksByNationality(na);
        } else if (!isEmptyString(queryString) && isEmptyString(na)) {
            Items = booksMapper.findByQuery(queryString);
        } else {
            Items = booksMapper.findByFilters(queryString, na);
        }
        PageInfo<Books> buyBookOnlyPageInfo = new PageInfo<>(Items);
        return new ResBean(true, null, buyBookOnlyPageInfo);
    }



    public boolean isEmptyString(String s) {
        return (s == null) || s.trim().equals("");
    }

}
